package njust.struts2.action;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import njust.dao.NeedsDao;
import njust.dao.UserDao;
import njust.domain.Goods;
import njust.domain.Needs;
import njust.domain.User;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class NeedsAction extends ActionSupport {

	private int pageNow;
	public int getPageNow() {
		return pageNow;
	}



	public void setPageNow(int pageNow) {
		this.pageNow = pageNow;
	}

	NeedsDao needsDao;
	String message;
	UserDao userDao;
	Needs needs;
	String userName;

	public String addNeeds() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		request.setCharacterEncoding("utf-8");
		response.setContentType("textml;charset=utf-8");
		PrintWriter out = response.getWriter();
		User user=(User) ActionContext.getContext().getSession().get("user");
		needs.setTime(new java.sql.Timestamp(Calendar.getInstance().getTime()
				.getTime()));
		needs.setUser(user);

		if (needsDao.addNeeds(needs)) {
			out.println(1);
		} else {
			out.println(0);
		}
		out.flush();
		out.close();
		return null;
	}


	
	public String getPageNeeds()
	{
		List<Needs> pageNeeds=needsDao.getNeedsByPage(10, pageNow);
		int sum=needsDao.pageTotle(10,pageNow);
		ActionContext.getContext().put("needsList", pageNeeds);
		ActionContext.getContext().put("sum", sum);
		ActionContext.getContext().put("pageNow",pageNow);
		ActionContext.getContext().put("jspnum", 3);
		return "getallneedsOK"; 
	}
	
	
	public String deleteImage(int id) {
		if (needsDao.deleteNeeds(id)) {
			message = "删除成功";
			return "deleteneedsok";
		} else {
			message = "删除失败";
			return "deleteneedsrror";
		}
	}

	public String getAllNeeds() {
		List<Needs> needs = new ArrayList();
		needs = needsDao.getAllNeeds();
        ActionContext.getContext().put("needsList",needs);
        
		return "getallneedsOK";
	}

	
	

	public String getNeedsById(int id) {
		needs = needsDao.getNeedsById(id);
		if (needs != null)
			return "getNeedsOK";
		else
			return "getNeedsError";
	}

	public NeedsDao getNeedsDao() {
		return needsDao;
	}

	public void setNeedsDao(NeedsDao needsDao) {
		this.needsDao = needsDao;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public Needs getNeeds() {
		return needs;
	}

	public void setNeeds(Needs needs) {
		this.needs = needs;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

}
